package cn.hwadee.muying.recommend.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @创建人 skiner
 * @创建时间 2018/8/14
 * @描述 单例模式
 */
public class SqlSessionFactoryUtils {

    private static SqlSessionFactory sqlSessionFactory = null;

    public static synchronized SqlSessionFactory getSqlSessionFactory(){
        //非空就返回
        if (sqlSessionFactory != null) {
            return sqlSessionFactory;
        }
        //获取配置
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSessionFactory;
    }

    public static SqlSession openSession(){
        if (sqlSessionFactory == null) {
            getSqlSessionFactory();
        }
        return sqlSessionFactory.openSession();
    }
}
